package com.xzh.wms.service;

import cn.hutool.core.date.DateUtil;
import cn.xzh.smart.core.util.UserSessionContext;
import com.xzh.wms.dao.OdoItemDao;
import com.xzh.wms.dao.OdoMasterDao;
import com.xzh.wms.dto.InventoryOptionDTO;
import com.xzh.wms.entity.OdoMaster;
import com.xzh.wms.entity.OdoMasterQuery;
import com.xzh.wms.event.InventoryOptionEvent;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
 /**
 * 出库单单头;(206_odo_master)表服务实现类
 * @author : heimi
 * @date : 2024-12-2
 */
@Service
public class OdoMasterService {
     
    @Autowired
    private OdoMasterDao odoMasterDao;

     @Autowired
     private OdoItemDao odoItemDao;

     @Autowired
     private ApplicationEventPublisher publisher;
    
    public List<OdoMaster> select(OdoMasterQuery query) {
        return odoMasterDao.select(query);
    }
    
    public Integer insert(OdoMaster odoMaster) {
        String odoId = "OD" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmssSSS");
        odoMaster.setId(odoId);
        odoMaster.getOdoItems().forEach(item->{
            item.setOdoId(odoId);
            item.setLastUpdateBy(UserSessionContext.get().getNickName());
        });
        OdoMasterService proxy = (OdoMasterService)(AopContext.currentProxy());
        proxy.save(odoMaster);
        return 0;
    }
     @Transactional()
     public void save(OdoMaster odoMaster) {
        odoItemDao.insertBatch(odoMaster.getOdoItems());
         odoMasterDao.insert(odoMaster);
         InventoryOptionDTO optionDTO = new InventoryOptionDTO().builder().OptionType("saleOut").refId(odoMaster.getId()).build();
         InventoryOptionEvent event = new InventoryOptionEvent(optionDTO);
         publisher.publishEvent(event);
     }
    
    public Integer update(OdoMaster odoMaster) {
        return odoMasterDao.update(odoMaster);
    }
    
    public Integer delete(Integer id) {
        return odoMasterDao.delete(id);
    }
    
 
}